#!/bin/bash
# Zookeeper集群管理脚本 (单机多实例)
# 用法: ./zk-cluster.sh [start|stop|status|restart]

# 定义实例配置
declare -A instances=(
  [1]="zookeeper1"  # 实例1配置目录
  [2]="zookeeper2"  # 实例2配置目录
  [3]="zookeeper3"  # 实例3配置目录
)

ZK_HOME="/opt/kafka"  # Zookeeper安装目录

case "$1" in
  start)
    echo "正在启动Zookeeper集群..."
    for id in "${!instances[@]}"; do
      cfg="${instances[$id]}"
      echo "启动实例 $id (配置: $cfg)..."
      "$ZK_HOME/$cfg/bin/zkServer.sh" start "$ZK_HOME/$cfg/conf/zoo.cfg"
    done
    ;;

  stop)
    echo "正在停止Zookeeper集群..."
    for id in "${!instances[@]}"; do
      cfg="${instances[$id]}"
      echo "停止实例 $id (配置: $cfg)..."
      "$ZK_HOME/$cfg/bin/zkServer.sh" stop "$ZK_HOME/$cfg/conf/zoo.cfg"
    done
    ;;

  status)
    for id in "${!instances[@]}"; do
      cfg="${instances[$id]}"
      echo -n "实例 $id (配置: $cfg) 状态: "
      "$ZK_HOME/$cfg/bin/zkServer.sh" status "$ZK_HOME/$cfg/conf/zoo.cfg" 2>&1 | grep Mode
    done
    ;;

  restart)
    $0 stop
    sleep 3
    $0 start
    ;;

  *)
    echo "用法: $0 {start|stop|status|restart}"
    exit 1
esac

exit 0